package com.cgg.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgg.order.mapper.OrderMapper;
import com.cgg.order.service.OrderService;
import com.cgg.order.vo.ExchangeOrder;
import com.cgg.stock.client.TradeClient;
import com.cgg.stock.client.UserClient;
import com.cgg.stock.common.exception.StockErrorException;
import com.cgg.stock.common.exception.UserErrorException;
import com.cgg.stock.common.pojo.Order;
import com.cgg.stock.common.pojo.User;
import com.cgg.stock.common.util.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@Slf4j
public class OrderServiceImpl  extends ServiceImpl<OrderMapper, Order> implements OrderService{

    private final BigDecimal TEN_PERCENT = BigDecimal.valueOf(0.1);

    private final int ORDER_TYPE_SELL = 1;
    private final int ORDER_TYPE_BUY = 0;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserClient userClient;

    @Autowired
    private TradeClient tradeClient;

    @Override
    public void addOrder(ExchangeOrder exchangeOrder) throws Exception {

        //判断订单是否合法
            //1.用户是否存在
            //2.用户金额是否充足
            //3.目标股票是否合法
            //4.用户标价是否合法


        if (exchangeOrder.getUserAccount()==null){
            throw new UserErrorException();
        }
        if (exchangeOrder.getStockId()==null){
            throw new StockErrorException();
        }
        if ((exchangeOrder.getPrice()).compareTo(exchangeOrder.getStockPrice().add(exchangeOrder.getStockPrice().multiply(TEN_PERCENT))) == 1 ||
                (exchangeOrder.getPrice()).compareTo(exchangeOrder.getStockPrice().subtract(exchangeOrder.getStockPrice().multiply(TEN_PERCENT))) == -1){
            throw new StockErrorException("出价超出现价10%，请重新出价");
        }

        User user =userClient.queryUserById(exchangeOrder.getUserAccount());
        if (user==null) throw new UserErrorException("用户不存在");



        Order order = new Order();

        //设置订单时间
        BeanUtil.copyProperties(exchangeOrder,order);

        Date date = new Date(System.currentTimeMillis());
        order.setRegisterOrderTime(date);

        //判断订单类型
        //将订单添加入队列
        //发送请求模拟撮合交易
        log.info("redisTemplate:{}",redisTemplate);
        if (exchangeOrder.getType()==ORDER_TYPE_SELL){
            redisTemplate.opsForZSet().add("sellQueue:" +order.getStockId(),order,order.getPrice().doubleValue());
            tradeClient.matchSell(order);
        }else if (exchangeOrder.getType()==ORDER_TYPE_BUY){
            if (user.getAvailableAmount().compareTo(exchangeOrder.getPrice().multiply(BigDecimal.valueOf(exchangeOrder.getNum()))) == -1) throw new UserErrorException("账户余额不足");
            redisTemplate.opsForZSet().add("buyQueue:"+order.getStockId(),order,order.getPrice().doubleValue());
            //（买）扣除用户相应金额
            synchronized (this){
                userClient.ChangeAccountBalance(user.getAccount(),order.getPrice(),order.getNum());
            }
            tradeClient.matchBuy(order);
        }



    }

}
